'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';

interface DashboardStats {
  productsCount: number;
  inventoryCount: number;
  ordersCount: number;
  customersCount: number;
  recentOrders: Array<{
    id: number;
    orderNumber: string;
    status: string;
    totalAmount: number;
  }>;
  lowStockItems: Array<{
    id: number;
    name: string;
    quantity: number;
  }>;
}

function DashboardCard({ title, description, href, count }: {
  title: string;
  description: string;
  href: string;
  count: number;
}) {
  return (
    <Link href={href} className="bg-white rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-xl font-semibold">{title}</h3>
        <span className="bg-blue-100 text-blue-800 text-sm px-3 py-1 rounded-full">
          {count}
        </span>
      </div>
      <p className="text-gray-600 text-sm">{description}</p>
    </Link>
  );
}

export default function DashboardStats() {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    fetchDashboardStats();
  }, []);

  const fetchDashboardStats = async () => {
    try {
      const response = await fetch('/api/dashboard/stats');
      if (!response.ok) {
        throw new Error('获取统计数据失败');
      }
      const data = await response.json();
      setStats(data);
    } catch (error) {
      console.error('获取仪表板数据失败:', error);
      setError('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  const getStatusColor = (status: string) => {
    const colorMap = {
      'pending': 'text-yellow-600',
      'paid': 'text-green-600',
      'shipped': 'text-blue-600',
      'delivered': 'text-gray-600',
      'cancelled': 'text-red-600'
    };
    return colorMap[status as keyof typeof colorMap] || 'text-gray-600';
  };

  const getStatusText = (status: string) => {
    const statusMap = {
      'pending': '待支付',
      'paid': '已支付',
      'shipped': '已发货',
      'delivered': '已交付',
      'cancelled': '已取消'
    };
    return statusMap[status as keyof typeof statusMap] || status;
  };

  const getStockColor = (quantity: number) => {
    if (quantity <= 2) return 'text-red-600';
    if (quantity <= 5) return 'text-orange-600';
    if (quantity <= 10) return 'text-yellow-600';
    return 'text-green-600';
  };

  if (loading) return <div className="p-8">加载中...</div>;
  if (error) return <div className="p-8 text-red-600">{error}</div>;
  if (!stats) return <div className="p-8">暂无数据</div>;

  return (
    <>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <DashboardCard
          title="产品管理"
          description="管理产品目录和信息"
          href="/products"
          count={stats.productsCount}
        />
        
        <DashboardCard
          title="库存管理"
          description="查看和更新库存数量"
          href="/inventory"
          count={stats.inventoryCount}
        />
        
        <DashboardCard
          title="订单管理"
          description="处理客户订单"
          href="/orders"
          count={stats.ordersCount}
        />
        
        <DashboardCard
          title="客户管理"
          description="管理客户信息"
          href="/customers"
          count={stats.customersCount}
        />
      </div>

      <div className="mt-12 grid grid-cols-1 lg:grid-cols-2 gap-8">
        <div className="bg-white rounded-lg shadow-md p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-semibold">最近订单</h2>
            <Link 
              href="/orders" 
              className="text-blue-600 hover:text-blue-800 text-sm hover:underline"
            >
              查看全部 →
            </Link>
          </div>
          <div className="space-y-3">
            {stats.recentOrders.length > 0 ? (
              stats.recentOrders.map((order) => (
                <div key={order.id} className="flex justify-between items-center py-2 border-b">
                  <Link 
                    href={`/orders/${order.id}`}
                    className="text-sm text-blue-600 hover:text-blue-800 hover:underline"
                  >
                    ORD-{order.orderNumber.toString().padStart(6, '0')}
                  </Link>
                  <span className={`text-sm ${getStatusColor(order.status)}`}>
                    {getStatusText(order.status)}
                  </span>
                  <span className="text-sm">¥{order.totalAmount}</span>
                </div>
              ))
            ) : (
              <div className="text-center text-gray-500 py-4">暂无订单</div>
            )}
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-md p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-semibold">库存预警</h2>
            <Link 
              href="/inventory" 
              className="text-blue-600 hover:text-blue-800 text-sm hover:underline"
            >
              管理库存 →
            </Link>
          </div>
          <div className="space-y-3">
            {stats.lowStockItems.length > 0 ? (
              stats.lowStockItems.map((item) => (
                <div key={item.id} className="flex justify-between items-center py-2 border-b">
                  <Link 
                    href={`/products/${item.id}`}
                    className="text-sm text-blue-600 hover:text-blue-800 hover:underline"
                  >
                    {item.name}
                  </Link>
                  <span className={`text-sm ${getStockColor(item.quantity)}`}>
                    库存: {item.quantity}
                  </span>
                </div>
              ))
            ) : (
              <div className="text-center text-green-500 py-4">库存充足</div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}